//
//  CRTopicViewController.m
//  CRChatRoom
//
//  Created by CuiFengshuai on 15/11/27.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRTopicViewController.h"
#import "AFNetworking.h"
#import "CRTopicCell.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "MJRefresh.h"
#import "CRComment.h"
#import "CRCommentViewController.h"
#import "SDImageCache.h"
#import "CRPlayerManager.h"
@interface CRTopicViewController () 
/** 管理者 */
@property (nonatomic, weak) AFHTTPSessionManager *manager;

@property (nonatomic, weak) CRPlayerManager *plarManager;
/** 所有的帖子数据 */
@property (nonatomic, strong) NSMutableArray *topics;
/** maxtime */
@property (nonatomic, copy) NSString *maxtime;

@end

@implementation CRTopicViewController
// cell 的重用标识
static NSString * const CRCellId = @"topic";

#pragma mark >>>> 懒加载
- (CRTopicType)type {
    return 0;
}
- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (CRPlayerManager *)plarManager {
    if (!_plarManager) {
        _plarManager = [CRPlayerManager defaultManager];
    }
    return _plarManager;
}

#pragma mark >>>> 系统方法
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 自定义控件初始化
    [self setupSubViews];
    
    // 初始化数据模型
    [self initData];
}

#pragma mark >>>> 初始化方法
/**
 *  自定义控件初始化
 */
- (void)setupSubViews {
    [self setupTableView];
}

/**
 *  初始化数据模型
 */
- (void)initData {
    [self setupRefresh];
}

- (void)setupRefresh {
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    
    //  上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopices)];
}

- (void)setupTableView {
    // 注册 cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CRTopicCell class]) bundle:nil] forCellReuseIdentifier:CRCellId];
    // 设置tableView的上下内边距
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat top = CRTitlesViewH + kDefaultNavigationBarMaxY;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    
    // 设置滚动条的内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    // 背景色
    self.tableView.backgroundColor = CRGlobalBg;
    // 分割线样式
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
#pragma mark >>>> 事件监听方法
/**
 *  下拉刷新
 */
- (void)loadNewTopics {
    
    // 取消之前的所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"newlist";
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    
    // 发送请求
    CRWeakSelf;
    [self.manager GET:CRBaseURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        // 存储maxtime：方便加载下一页的数据
        weakSelf.maxtime = responseObject[@"info"][@"maxtime"];
        
        // 字典 ->模型
        weakSelf.topics = [CRTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 刷新表格
            [weakSelf.tableView reloadData];
        });
        
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
        //如果是取消了任务 直接返回
        if (error.code == NSURLErrorCancelled) {
            return ;
        }
        
        [MBProgressHUD showError:@"下拉刷新失败"];
    }];
    
}
/**
 *  上拉加载
 */
- (void)loadMoreTopices {

    // 取消之前的所有的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    // 请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"newlist";
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    params[@"maxtime"] = self.maxtime;
    
    // 发送请求
    CRWeakSelf;
    [self.manager GET:CRBaseURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        weakSelf.maxtime = responseObject[@"info"][@"maxtime"];
        
        // 字典转换成模型
        NSArray *newTopics = [CRTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        // 将newTopics中的所有元素添加到weakSelf.topics中
        [weakSelf.topics addObjectsFromArray:newTopics];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 刷新表格
            [weakSelf.tableView reloadData];
        });
        
        // 结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
        
        [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
        //如果是取消了任务 直接返回
        if (error.code == NSURLErrorCancelled) {
            return ;
        }
        
        [MBProgressHUD showError:@"上拉加载失败"];
    }];
    
}
#pragma mark >>>> 实现代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CRTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:CRCellId];
    
    cell.topic = self.topics[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 模型数据
    CRTopic *topic = self.topics[indexPath.row];
    
    // 返回这个模型对应的cell的高度
    return topic.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CRCommentViewController *commentVC = [[CRCommentViewController alloc] init];
    commentVC.topic = self.topics[indexPath.row];
    commentVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:commentVC animated:YES];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    CRPlayerManager *manager = [CRPlayerManager defaultManager];
    if (!manager.isPlaying) {
        return;
    }
    
    [manager didToStop];
}
#pragma mark >>>> 其他方法


@end
